<template>
  <van-button
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    v-if="!isFollowed"
    :loading="loading"
    @click="onFollow"
    >关注</van-button
  >
  <van-button
    v-else
    class="follow-btn"
    :loading="loading"
    @click="onFollow"
    round
    size="small"
    >已关注</van-button
  >
</template>

<script>
// 关注 / 取关用户
import { addFollow, deleteFollow } from '@/api/user'
export default {
  name: 'FollowUser',
  components: {

  },
  // 可以通过 model 修改 v-model 的规则名称(默认的 value 和 input)
  model: {
    prop: 'isFollowed',
    event: 'update-isFollowed'
  },
  data () {
    return {
      loading: false
    }
  },
  created () {

  },
  props: {
    isFollowed: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [String, Number, Object],
      required: true
    }
  },
  methods: {
    async onFollow () {
      // 按钮点击响应状态
      this.loading = true
      try {
        if (this.isFollowed) {
          // 关注了,取关操作
          await deleteFollow(this.userId)
          this.$toast('取关成功')
        } else {
          // 没关注,添加关注
          await addFollow(this.userId)
          this.$toast('关注成功')
        }
        // 更新数据状态,以达到按钮状态切换的目的
        // this.isFollowed = !this.isFollowed
        this.$emit('update-isFollowed', !this.isFollowed)
      } catch (error) {
        console.error(error)
        if (this.response.status === 400) {
          this.$toast('不能关注自己,撒比!')
        }
        this.$toast('操作失败,请重试!')
      }
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
